import React, {useState,useEffect} from 'react'
import './LayerCellGeneral.css';


import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faEye, faEyeSlash , faWindowClose , faInfoCircle , faPen , faSlidersH} from '@fortawesome/free-solid-svg-icons'
import StyleLinear from './StyleLinear';
import StyleDiscrete from './StyleDiscrete'
import StyleExact from './StyleExact'
import StyleGray from './StyleGray'
import StyleRGB from './StyleRGB'
import StyleRGBA from './StyleRGBA'

//全部图层种类 wms静态WMS产品 xyz静态XYZ产品 pe系统直接产品 pes系统脚本产品 us用户脚本差评 ud用户直接数据


// 通用图层单元格
//props.lyrParams : opacity(0-1),visible,productDisplay.type('xyz','wms','pe','pes','us','ud','pgm')
// props.appDateA={props.appDateA}
// props.appDateB={props.appDateB}
// props.isGroupA={props.isActiveGroupA}
//props.onLayerCellEditStyleClickedCallback 编辑渲染方案的回调函数
//props.onLayerCellSDUIClickedCallback
// props.onLayerCellExportClick(props.lyrParams)}
// props.onLayerCellStatisticClick(props.lyrParams)}
// props.onLayerCellCompositeClick(props.lyrParams)}
// props.onLayerCellSerialClick(props.lyrParams)}
// props.onLayerCellScriptClick(props.lyrParams)
// props.onLayerCellGotsClick(props.lyrParams, gotsMeta)
// props.onLayerCellOmcClick
function LayerCellGeneral(props) {
    const [visible, setVisible] = useState(props.lyrParams.visible);
    const [showToolbar, setShowToolbar] = useState(false);
    const [styleObj, setStyleObj] = useState(null);
    const [layerDescStr, setLayerDescStr] = useState("") ;
    const [layerFlag, setLayerFlag] = useState(0);// 0-noflag , 1-warn , 2-error

    const getAndSetStyle = async function(styleid){
        //http://localhost/pe/style/get/{styleid}
        const turl = global.g_serverAPIRoot + "style/detail/"+styleid ;
        const response =await fetch(turl);
        const resobj =await response.json() ;
        const styleRecordObj = resobj.data;
        const styleobj = JSON.parse(styleRecordObj.styleContent);
        setStyleObj(styleobj);
    }
    useEffect(() => {
        if( props.lyrParams.styleid>0 ){
            getAndSetStyle(props.lyrParams.styleid);
        }
    }, [props.lyrParams])


    useEffect(() => {
        setVisible(props.lyrParams.visible) ;
    }, [props.lyrParams.visible])

    /// tag is ERROR WARN or INFO
    const extractTagInnerText = function(msg , tag  ) {

        if( tag.length===0 ) return "" ;
        const tag0 = '['+tag+']' ;
        const tag1 = '[/'+tag+']' ;
        if(typeof msg==='undefined') {
            return "" ;
        }else {
            const index0 = msg.indexOf(tag0) ;
            const index1 = msg.indexOf(tag1) ;
            if( index0 >=0 && index1 >=0 && index1 > index0 ){
                return msg.substring( index0 + tag0.length , index1) ;
            }else{
                return "" ;
            }
        }
    }

    //private
    //[ERROR]...[/ERROR], [WARN]...[/WARN], [INFO]...[/INFO] 按顺序只分析第一个出现的标签
    // params: string 
    // return: {flag:0,desc:'...'} or null
    const helperExtractLayerFlagAndDescStr = function( inputString ){
        let res1 = extractTagInnerText(inputString,"ERROR") ;
        if( res1 !== "" ){
            return {flag:2 , desc:res1} ;
        }else{
            res1 = extractTagInnerText(inputString,"WARN") ;
            if( res1 !== "" ){
                return {flag:1,desc:res1} ;
            }else{
                res1 = extractTagInnerText(inputString,"INFO") ;
                if( res1!=="" ){
                    return {flag:0,desc:res1} ;
                }else{
                    return {flag:0,desc:inputString} ;
                }
            }
        }
    }
    

    
    //private
	//将Javascript Date对象转换成 yyyyMMdd000000 格式 , HHmmss使用0填充 该函数在MapPanel.js
	const helperConvertJsDate2yyyyMMdd = function (dateObj) {
		let ymd14 = dateObj.getFullYear() * 10000;
		ymd14 += (dateObj.getMonth() + 1) * 100;
		ymd14 += dateObj.getDate();
		ymd14 = ymd14 * 1000000;
		return ymd14;
	}

    //private 为pgm图层更新时间和图层描述
	const helperSetLayerFlagAndDescByPGM = async function(sid,datetime1){
		const url1= global.g_serverAPIRoot + "scripts/pgminfo/?sid=" + sid + "&datetime=" + datetime1 ;
		const response = await fetch(url1) ; //GET
		const jsonObj = await response.json() ;
	   	if( typeof jsonObj !== 'undefined' && jsonObj!==null ){
			if( jsonObj.state===0 ){
                const pgminfo1 = JSON.parse(jsonObj.data) ;
				const res1 = helperExtractLayerFlagAndDescStr(pgminfo1.desc) ;
                setLayerFlag(res1.flag) ;
                setLayerDescStr(res1.desc) ;
			}else{
				setLayerFlag(2) ;
                setLayerDescStr("PGM info null") ;
			}
		}else{
			setLayerFlag(2) ;
            setLayerDescStr("PGM info null") ;
		}
	}

    /// 2022-7-10
	/// 针对pe,us,pes,ud 几个产品通过获取0号瓦片的日志来更新图层flag和日志信息
	/// 瓦片计算日志信息 
	/// http://192.168.56.103:15900/pe/product/wmtstclog?pid=1&
	///        datetime=20200900000000&styleid=0&roiid=null
	/// http://192.168.56.103:15900/pe/scripts/wmtstclog?sid=2&
	///        datetime=20200900000000&styleid=0&sdui=null&utime=1
	/// 如果没有http异常返回{state,message,data}对象，反之返回null
	const fetchZeroLogInfoAndSetIt = async ( ymd14 , lyrParams) => {
        const datetime1 = ymd14 ;
		let url1 = "" ;
		if( typeof lyrParams === 'undefined' ){
			return ;
		}
		let timestamp1 = parseInt(Date.now()/1000) ;
		if( lyrParams.productDisplay.type==='pe' || lyrParams.productDisplay.type==='ud')
		{
			url1 = global.g_serverAPIRoot + "product/wmtstclog?pid=" + lyrParams.pid 
				+ "&datetime=" + datetime1
				+ "&styleid=" + lyrParams.styleid 
				+ "&roiid=" + "null";
		}else if(lyrParams.productDisplay.type==='pes') {
			const paramsStr = lyrParams.productDisplay.params ;
			if( paramsStr.length > 1 ){
				let slimSdui = {} ;
				if (typeof lyrParams.sdui !== 'undefined' && lyrParams.sdui !== null) {
					for (let key in lyrParams.sdui) {
						slimSdui[key] = { val: lyrParams.sdui[key].val };
					}
				}
				const tempJsonObj1 = JSON.parse(paramsStr) ;
				let tempSid1 = tempJsonObj1.sid ;
				let tempStyleid1 = ( typeof tempJsonObj1.styleid==='undefined' )?0:tempJsonObj1.styleid ;
				url1 = global.g_serverAPIRoot + "scripts/wmtstclog?sid=" + tempSid1 
				+ "&datetime=" + datetime1
				+ "&styleid=" + tempStyleid1   
				+ "&sdui=" + JSON.stringify(slimSdui) 
				+ "&utime=" + timestamp1 ;
			}else{
				console.log("a pes layer but not valid params for sid:'"+paramsStr+"'.") ;
				return ;
			}
		}else if( lyrParams.productDisplay.type==='us' ){
			let slimSdui = {} ;
			if (typeof lyrParams.sdui !== 'undefined' && lyrParams.sdui !== null) {
				for (let key in lyrParams.sdui) {
					slimSdui[key] = { val: lyrParams.sdui[key].val };
				}
			}
			url1 = global.g_serverAPIRoot + "scripts/wmtstclog?sid=" 
                + lyrParams.productDisplay.dpid 
				+ "&datetime=" + datetime1
				+ "&styleid=0"   
				+ "&sdui=" + JSON.stringify(slimSdui) 
				+ "&utime=" + timestamp1 ;
		}else{
			return  ;
		}
		url1 = encodeURI(url1) ;
		fetch(url1)  //GET
		.then(response=>response.json())
		.then(result => {
			const loginfo1 = result ;
            if( loginfo1===null  )
            {
                setLayerFlag(0) ;
                setLayerDescStr("") ;
            }else {
                //[ERROR]...[/ERROR], [WARN]...[/WARN], [INFO]...[/INFO] 按顺序只分析第一个出现的标签
                const res1 = helperExtractLayerFlagAndDescStr(loginfo1.message) ;
                setLayerFlag(res1.flag) ;
                setLayerDescStr(res1.desc) ;
            } 

		}).catch(err=> {
			console.log("loginfo is null");
		});
	}

    

    useEffect( () => {
        if( typeof props.lyrParams.productDisplay !== 'undefined' ){
            let useDate = props.appDateA ;
            if( props.isGroupA===false ) {
                useDate = props.appDateB ;
            }
            const ymd14 = helperConvertJsDate2yyyyMMdd(useDate) ;
            if( props.lyrParams.productDisplay.type === 'pgm')
            {
                const displayParamsObj = JSON.parse(props.lyrParams.productDisplay.params) ;
                const sid1 = displayParamsObj.sid ;                
                helperSetLayerFlagAndDescByPGM(sid1,ymd14) ;
            }
            else if(props.lyrParams.productDisplay.type==='pe' 
            || props.lyrParams.productDisplay.type==='pes' 
            || props.lyrParams.productDisplay.type==='ud' 
            || props.lyrParams.productDisplay.type==='us' 
            ){
                fetchZeroLogInfoAndSetIt(ymd14 , props.lyrParams ) ;
                
            }
        }else{
            setLayerFlag(0) ;
            setLayerDescStr("") ;
        }
    }, [props.appDateA,props.appDateB,props.isGroupA])
    

    const onToggleVisibleClicked = function()
    {
        /// 回调图层显示隐藏函数
        props.onToggleLayerVisible(props.lyrParams.displayid) ;
    }
    
    //鼠标移入图层单元格显示工具栏
    const onMouseEnteredHappenned = function(){
        setShowToolbar(true) ;
    }

    //鼠标移除图层单元格隐藏工具栏
    const onMouseExitedHappenned = function(){
        setShowToolbar(false) ;
    }

    // 关闭图层按钮点击
    const onCloseButtonClicked = function() {
        props.onCloseButtonClicked( props.lyrParams.displayid ) ;
    }

    // 点击编辑渲染方案按钮
    const onLayerCellEditStyleClickedCallback = function() {
        props.onLayerCellEditStyleClickedCallback(props.lyrParams.displayid) ;

    }



    return (
        <div className={ (visible===true)?'LayerCellGeneral':'LayerCellGeneral Invisible'} onMouseLeave={onMouseExitedHappenned} onMouseEnter={onMouseEnteredHappenned}>
            {/* 显示隐藏图标 */}
            <div className="LayerCellGeneralVisible" onClick={onToggleVisibleClicked} >
                {
                    (visible===true)? <FontAwesomeIcon icon={faEye} />: <FontAwesomeIcon icon={faEyeSlash} />
                }
            </div>

            {/* 单元格内容 */}
            <div className="LayerCellGeneralContent">
                {/* error or warning message flag */}
                {
                    (layerFlag>0)?(<div className="LayerCellFlag"><div>!</div></div>):""
                }
                
                <h3>{props.lyrParams.productDisplay.productname}</h3>
                <h4>{props.lyrParams.productDisplay.subtitle}</h4>
                
                <h5>{layerDescStr}</h5>
                
                {/* 图例内容 pe ss us */}
                <div className="StyleContainer">
                    {
                        (styleObj!==null)? ( 
                            ( styleObj.type==='linear')?(
                                <StyleLinear styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    {
                        (styleObj!==null)? ( 
                            (styleObj.type==='discrete')?(
                                <StyleDiscrete styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    {
                        (styleObj!==null)? ( 
                            ( styleObj.type==='exact')?(
                                <StyleExact styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    {
                        (styleObj!==null)? ( 
                            (styleObj.type==='gray')?(
                                <StyleGray styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    {
                        (styleObj!==null)? ( 
                            (styleObj.type==='rgb')?(
                                <StyleRGB styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    {
                        (styleObj!==null)? ( 
                            (styleObj.type==='rgba')?(
                                <StyleRGBA styleObj={styleObj} />
                            ):""
                        ):""
                    }
                    
                </div>

                {/* 底部功能按钮 */}
                <div className="Footer">
                   
                    {
                        (props.lyrParams.productDisplay.type==='pe'
                            || props.lyrParams.productDisplay.type==='pes'
                            || props.lyrParams.productDisplay.type==='us'
                            || props.lyrParams.productDisplay.type==='ud'
                            )?
                        (
                            <>
                                {/* 在线作图 */}
                                <button className='GotsButton' 
                                onClick={()=>props.onLayerCellOmcClick(props.lyrParams)}
                                >
                                作图
                                </button>

                                {/* 数据导出 */}
                                <button className='GotsButton' 
                                onClick={()=>props.onLayerCellExportClick(props.lyrParams)}
                                >
                                数据导出
                                </button>

                                {/* 区域统计 */}
                                <button className='GotsButton' 
                                onClick={()=>props.onLayerCellStatisticClick(props.lyrParams)}
                                >
                                区域统计
                                </button>
                            </>
                        ):""

                    }

                    {
                        (props.lyrParams.productDisplay.type==='pe')?
                        (
                        <>
                            {/* 数据合成 */}
                            <button className='GotsButton' 
                            onClick={()=>props.onLayerCellCompositeClick(props.lyrParams)}
                            >
                            数据合成
                            </button>

                             {/* 序列分析 */}
                            <button className='GotsButton' 
                            onClick={()=>props.onLayerCellSerialClick(props.lyrParams)}
                            >
                            序列分析
                            </button>
                             
                        </>
                        ):""
                    }

                    {
                        props.lyrParams.gots.map( gotsItem => (
                            <button className='GotsButton' 
                            key={gotsItem.pk}
                            onClick={()=>props.onLayerCellGotsClick(props.lyrParams, gotsItem)}
                            >
                            {gotsItem.metavalstr}
                            </button>
                        ) )
                    }
                    
                </div>

                {/* 顶部按钮 */}
                <div className={ showToolbar?'Toolbar':'Toolbar Invisible' } >

                    {/* SCRIPT */}
                    {
                        (props.lyrParams.productDisplay.type==='us' )?(
                        <img src='./images/script.png' 
                        className="LayerCellToolbarButton" 
                        height='16'
                        onClick={()=>props.onLayerCellScriptClick(props.lyrParams )}
                        />
                        ):""
                    }
                    

                    {/* SDUI */}
                    {
                        (props.lyrParams.productDisplay.type==='pes'||props.lyrParams.productDisplay.type==='us' )?
                        (<img src='./images/sdui.png' className="LayerCellToolbarButton" onClick={()=>props.onLayerCellSDUIClickedCallback(props.lyrParams )}/>):"" 
                    }
                    
                    {/* STYLE */}
                    {
                        (props.lyrParams.productDisplay.type==='pe' || 
                            props.lyrParams.productDisplay.type==='pes' || 
                            props.lyrParams.productDisplay.type==='us' || 
                            props.lyrParams.productDisplay.type==='ud')?
                        (<FontAwesomeIcon icon={faPen} className="LayerCellToolbarButton" onClick={onLayerCellEditStyleClickedCallback}/>):""
                    }
                    
                    <FontAwesomeIcon icon={faInfoCircle} className="LayerCellToolbarButton"/>

                    {/* ALPHA */}
                    <FontAwesomeIcon icon={faSlidersH} className="LayerCellToolbarButton"/>


                    <FontAwesomeIcon icon={faWindowClose} className="LayerCellToolbarButton" onClick={onCloseButtonClicked} />
                </div>

            </div>
            
        </div>
    )
}

export default LayerCellGeneral





// const testStyleobj1 = {
//     type:'linear',
//     bands:[0],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[  
//         {val:1,r:215,g:25 ,b:28,a:255,lbl:'0.1'},
//         {val:50,  r:253,g:174,b:97,a:255,lbl:'0.5'},
//         {val:100, r:255,g:255,b:191,a:255,lbl:'10.0'},
//         {val:200, r:171,g:221,b:164,a:255,lbl:'20.0'},
//         {val:300, r:43, g:131,b:186,a:255,lbl:'30.0(K)'}
//     ],
//     vranges:[
//     ]
// }

// const testStyleobj2 = {
//     type:'discrete',
//     bands:[0],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[  
//         {val:1,r:215,g:25 ,b:28,a:255,lbl:'0.1'},
//         {val:50,  r:253,g:174,b:97,a:255,lbl:'0.5'},
//         {val:100, r:255,g:255,b:191,a:255,lbl:'10.0'},
//         {val:200, r:171,g:221,b:164,a:255,lbl:'20.0'},
//         {val:300, r:43, g:131,b:186,a:255,lbl:'30.0(K)'}
//     ],
//     vranges:[
//     ]
// }

// const testStyleobj3 = {
//     type:'exact',
//     bands:[0],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[  
//         {val:1,r:128,g:0 ,b:0,a:255,lbl:'建筑'},
//         {val:50,  r:0,g:128,b:0,a:255,lbl:'水华'},
//         {val:100, r:0,g:0,b:128,a:255,lbl:'沙漠'},
//         {val:1,r:128,g:128 ,b:0,a:255,lbl:'裸土'},
//         {val:50,  r:0,g:128,b:128,a:255,lbl:'农田'},
//         {val:100, r:255,g:0,b:0,a:255,lbl:'灌木'},
//         {val:1,r:0,g:255 ,b:0,a:255,lbl:'森林'},
//         {val:50,  r:0,g:0,b:255,a:255,lbl:'水体'},
//         {val:100, r:0,g:0,b:128,a:255,lbl:'陆地'},
//         {val:1,r:128,g:0 ,b:0,a:255,lbl:'针叶林'},
//         {val:50,  r:0,g:128,b:0,a:255,lbl:'云'},
//         {val:100, r:0,g:0,b:128,a:255,lbl:'海洋'},
//         {val:30, r:176,g:176,b:30,a:255,lbl:'小麦'}
//     ],
//     vranges:[
//     ]
// }

// const testStyleobj4 = {
//     type:'gray',
//     bands:[0],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[],
//     vranges:[{"minval":0,"maxval":255}
//     ]
// }

// const testStyleobj5 = {
//     type:'rgb',
//     bands:[0,1,2],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[],
//     vranges:[{"minval":0,"maxval":200},{"minval":0,"maxval":300},{"minval":0,"maxval":400}
//     ]
// }

// const testStyleobj6 = {
//     type:'rgba',
//     bands:[3,2,1,0],
//     nodatacolor:{ val:-1,r:0,g:0,b:0,a:0,lbl:'fill'},
//     colors:[],
//     vranges:[{"minval":0,"maxval":100},{"minval":0,"maxval":200},{"minval":0,"maxval":300},{"minval":0,"maxval":400}
//     ]
// }